package com.xiaoh.nio;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * 使用一个Buffer完成文件读取
 *
 * @author xiaoH
 * @date 2020/4/29
 * @description
 */
public class NIOFileChannel03 {

    public static void main(String[] args) throws IOException {

        FileInputStream fileInputStream = new FileInputStream("1.txt");
        //通过fileInputStream获取对应的FileChannel -> FileChannelImpl
        FileChannel fileChannel01 = fileInputStream.getChannel();

        FileOutputStream fileOutputStream = new FileOutputStream("2.txt");
        FileChannel fileChannel02 = fileOutputStream.getChannel();

        //创建缓冲区
        ByteBuffer byteBuffer = ByteBuffer.allocate(512);

        while (true) {

            //这里又一个重要的操作
            byteBuffer.clear();//清空byteBuffer

            int read = fileChannel01.read(byteBuffer);
            System.out.println("read = " + read);
            if (read == -1) {//表示读取完毕
                break;
            }
            byteBuffer.flip();
            // 将buffer中的数据写入到fileChannel02中
            fileChannel02.write(byteBuffer);
        }

        //将byteBuffer的字节数据转成String
        System.out.println(new String(byteBuffer.array()));
        fileInputStream.close();

        //关闭相关的流
        fileInputStream.close();
        fileOutputStream.close();
    }
}
